#include "widget.h"
#include "ui_widget.h"
#include <QKeyEvent>
#include <QDebug>
#include <QTimer>
#include <QTime>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setFocusPolicy(Qt::ClickFocus);
    QTimer * timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Widget::slot_update_led);
    timer->start(10);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::keyPressEvent(QKeyEvent *event)
{
    qDebug() << "[Widget::keyPressEvent]: " <<event->key();
    bool b_upflag= false;
    bool b_downflag = false;
    bool b_leftflag = false;
    bool b_rightflag = false;
    if(event->key() == Qt::Key_Up){
        if(event->isAutoRepeat()){
            auto curpos = ui->pushButton->pos();
            curpos.setY(curpos.y()-5);
            ui->pushButton->move(curpos);
            return;
        }else{
            b_upflag = true;
        }
    }
    if(event->key() == Qt::Key_Left){
        if(event->isAutoRepeat()){
            auto curpos = ui->pushButton->pos();
            curpos.setX(curpos.x()-5);
            ui->pushButton->move(curpos);
            return;
        }else{
            b_leftflag = true;
        }
    }
    if(event->key() == Qt::Key_Down){
        if(event->isAutoRepeat()){
            auto curpos = ui->pushButton->pos();
            curpos.setY(curpos.y()+5);
            ui->pushButton->move(curpos);
            return;
        }else{
            b_downflag = true;
        }
    }
    if(event->key() == Qt::Key_Right){
        if(event->isAutoRepeat()){
            auto curpos = ui->pushButton->pos();
            curpos.setX(curpos.x()+5);
            ui->pushButton->move(curpos);
            return;
        }else{
            b_rightflag = true;
        }
    }
    auto curpos = ui->pushButton->pos();
    if(b_upflag){
        curpos.setY(curpos.y()-5);
    }
    if(b_downflag){
        curpos.setY(curpos.y()+5);
    }
    if(b_leftflag){
        curpos.setX(curpos.x()-5);
    }
    if(b_rightflag){
        curpos.setX(curpos.x()+5);
    }
    ui->pushButton->move(curpos);

    if(event->modifiers()==Qt::ControlModifier){
        if(event->key()==Qt::Key_M && windowState()!=Qt::WindowFullScreen){
            setWindowState(Qt::WindowFullScreen);
        }
    }

    if(event->key()==Qt::Key_Escape && windowState()==Qt::WindowFullScreen){
        setWindowState(Qt::WindowNoState);
    }
}

void Widget::slot_update_led()
{
    QTime time = QTime::currentTime();
    QString t2 = time.toString("hh:mm:ss:zzz").left(11);
    //auto t2 = t.left(11);
    if((time.second()%2) == 0){
        t2[2]=' ';
        t2[5]=' ';
        t2[8]=' ';
    }
    ui->lcdNumber->setDigitCount(t2.length());
    ui->lcdNumber->display(t2);
}
